package hichecker.ui.components.verifier.verifier_text_field;

import hichecker.ui.components.verifier.NumberVerifier;
import hichecker.ui.components.verifier.SemesterVerifier;
import hichecker.ui.components.verifier.StringVerifier;
import info.clearthought.layout.TableLayout;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.InputVerifier;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class VerifierTextField extends JPanel {
	public static enum InputType {
		NUMBER, SEMESTER, STRING
	};

	private AbstractVerifyAction action;
	private JLabel descriptionLabel, errorLabel;;
	private JTextField textField;

	public VerifierTextField(Object value, InputType type, String description,
			AbstractVerifyAction action) {
		this.action = action;

		descriptionLabel = new JLabel(description);

		errorLabel = new JLabel() {
			@Override
			public void setText(String text) {
				super.setText(text);
				setToolTipText(text == "" ? null : text);
			};
		};
		errorLabel.setForeground(Color.RED);

		textField = new JTextField(value == null ? "" : value.toString());
		textField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				processValue();
			}
		});
		switch (type) {
		case NUMBER:
			textField.setInputVerifier(new NumberVerifier(errorLabel));
			break;
		case SEMESTER:
			textField.setInputVerifier(new SemesterVerifier(errorLabel));
			break;
		case STRING:
			textField.setInputVerifier(new StringVerifier());
			break;
		}

		setMaximumSize(new Dimension(getMaximumSize().width, textField.getPreferredSize().height));

		setLayout(new TableLayout(new double[][] { { 170, 200, 10, TableLayout.FILL },
				{ textField.getPreferredSize().getHeight() } }));
		add(descriptionLabel, "0,0");
		add(textField, "1,0");
		add(errorLabel, "3,0");
	}

	private void processValue() {
		if (isCorrect())
			action.process(textField.getText());
	}

	public boolean isCorrect() {
		InputVerifier verifier = textField.getInputVerifier();
		return verifier == null ? false : verifier.verify(textField);
	}
}
